//
//  ActivityDetailVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/8/3.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "ActivityDetailVC.h"
#import "SignUpVC.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>

@interface ActivityDetailVC ()<UIWebViewDelegate>

@end

@implementation ActivityDetailVC
{
    UIWebView *_webView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = White_Color;
    self.title = @"活动详情";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(shareBtn)];
    [self requestForHtmlUrl];
    
    [self initBtnForSign];
}
- (void)requestForHtmlUrl{
    //参数
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
    [parameters setValue:self.activityId forKey:@"activityID"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/activity/getActivityHtml.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        NSDictionary *_responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
            
        }else{
            //请求成功
            NSString *_htmlStr = _responseDic[@"htmlURL"];
            //获取当前时间
            NSDate *currentDate = [NSDate date];//获取当前时间，日期
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"YYYYMMddHHmmssSSS"];
            NSString *dateString = [dateFormatter stringFromDate:currentDate];
            _htmlStr = [NSString stringWithFormat:@"%@%@%@",_htmlStr, @"?",dateString];
            [self initWebViewWithHtmlUrl:_htmlStr];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"HtmlUrl请求失败"];
    }];
}
- (void)initWebViewWithHtmlUrl:(NSString *)url{
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, KScreenWidth, KScreenHeight-44-64)];
    _webView.delegate = self;
    _webView.dataDetectorTypes = UIDataDetectorTypeNone;
    _webView.backgroundColor = White_Color;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [_webView loadRequest:request];
    [self.view addSubview:_webView];
}

#pragma - mark UIWebViewDelegate

//- (void)webViewDidFinishLoad:(UIWebView *)webView{
//    [_webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
//     "script.type = 'text/javascript';"
//     "script.text = \"function myFunction() { "   //定义myFunction方法
//     "var oMeta = document.createElement('meta');"
//     "oMeta.name = 'format-detection';"
//     "oMeta.content = 'telephone=no';"
//     "document.getElementsByTagName('head')[0].appendChild(oMeta);"
//     "}\";"
//     "document.getElementsByTagName('head')[0].appendChild(script);"];  //添加到head标签中
//    
//    [_webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];
//}

- (void)initBtnForSign{
    UIButton *signBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, KScreenHeight-44, KScreenWidth, 44)];
    NSString *str = [NSString readToNSDefaultsWithKey:kType];
    if ([str isEqual:@"0"]&&[self.status isEqualToString:@"1"]) {
        //0为俱乐部用户
        signBtn.backgroundColor = Gray_Color;
        [signBtn setTitle:@"报  名" forState:UIControlStateNormal];
    }
    if (![str isEqual:@"0"]&&[self.status isEqualToString:@"1"]) {
        signBtn.backgroundColor = Theme_Color;
        [signBtn setTitle:@"报  名" forState:UIControlStateNormal];
        [signBtn addTarget:self action:@selector(signBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    if ([self.status isEqualToString:@"3"]) {
        signBtn.backgroundColor = Gray_Color;
        [signBtn setTitle:@"已结束" forState:UIControlStateNormal];
    }
    if ([self.status isEqualToString:@"2"]) {
        signBtn.backgroundColor = Orange_Color;
        [signBtn setTitle:@"进行中" forState:UIControlStateNormal];
    }
    [signBtn setTitleColor:White_Color forState:UIControlStateNormal];
    [self.view addSubview:signBtn];
}
- (void)phoneAction{
    //拨打电话后不返回至应用
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://10086"]];
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:@"tel:10086"];// 貌似tel:// 或者 tel: 都行
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.view addSubview:callWebview];
}

- (void)signBtnAction{
    SignUpVC *vc = [[SignUpVC alloc]init];
    vc.activityId = self.activityId;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)shareBtn{
    //1、创建分享参数
    NSArray* imageArray = @[[UIImage imageNamed:@"logoo.png"]];
    
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"向你分享了一个活动"
                                         images:imageArray
                                            url:[NSURL URLWithString:self.activityHtmlUrlStr]
                                          title:@"羣图自驾游"
                                           type:SSDKContentTypeAuto];
        //2、分享（可以弹出我们的分享菜单和编辑界面）
        [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"确定"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           default:
                               break;
                       }
                   
                       }];
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
